package cn.neusoft.service.impl;

import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.service.IVerifyCodeService;
import cn.neusoft.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 生成图形化验证码
     * @param key
     */
    @Override
    public String graph(String key) {

        //产生四位验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //存放redis
        redisTemplate.opsForValue().set(key, code,
                5, TimeUnit.MINUTES);

        //4.把验证码的值合并到图片
        //5.把图片使用Base64编码
        //6.返回base64编码的字符串
        try {
            String base64Str = VerifyCodeUtils.VerifyCode(
                    140,
                    40,
                    code);
            base64Str = base64Str.replaceAll("\r\n","");
            return "data:image/jpg;base64,"+base64Str;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(AppExceptionCodeMsg.GENERATE_GRAPH_VERIFYCODE_FAIL);
        }

    }

    /**
     * 验证码的验证
     * @param key
     * @param code
     * @return
     */
    @Override
    public boolean valide(String key, String code) {

        //通过key[和生成时要保持一致]  获取redis中存储的验证码
        Object o = redisTemplate.opsForValue().get(key);

        //如果获取不到 报超时异常
        if (o==null){
            throw new AppException(AppExceptionCodeMsg.CODE_TIMEOUT);
        }

        System.out.println("-----获取到验证码--"+key+"---"+o.toString());

        //判断redis中获取的验证码和传递过来的验证码是否一致
        if(!o.toString().equals(code)){
            throw new AppException(AppExceptionCodeMsg.INVALID_CODE);
        }

        return true;
    }
}